var app = getApp();
var QQMapWX = require('../../common/qqmap-wx-jssdk.js');
var demo = new QQMapWX({
  key: '4FWBZ-C3U3G-N6IQW-IRZNQ-LLZ2S-2QBJM' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    authStatus: true,
    wxBind: true,
    bagStatus: true,
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    circular: true,
    interval: 3000,
    duration: 800,
    previousMargin: 0,
    nextMargin: 0,
    winWidth: 0,
    winHeight: 0,
    flag: false,
    show: false,
    list_array: [{
      title: '搜产品',
      image: 'https://lg-0nsng10k-1256175049.cos.ap-shanghai.myqcloud.com/index_home_search_product.png',
      identify: 0,
      hide: true
    }, {
      title: '查公司',
      image: 'https://lg-0nsng10k-1256175049.cos.ap-shanghai.myqcloud.com/index_home_search_company.png',
      identify: 1,
      hide: true
    }, {
      title: '找精英',
      image: 'https://lg-0nsng10k-1256175049.cos.ap-shanghai.myqcloud.com/index_home_find_elites.png',
      identify: 2,
      hide: true
    }, {
      title: '抢客户',
      image: 'https://lg-0nsng10k-1256175049.cos.ap-shanghai.myqcloud.com/index_home_find_client.png',
      identify: 3,
      hide: true
    }, {
      title: '展业地图',
      image: 'https://lg-0nsng10k-1256175049.cos.ap-shanghai.myqcloud.com/index_home_peer_map.png',
      identify: 4
    }, {
      title: '活动交流',
      image: 'https://lg-0nsng10k-1256175049.cos.ap-shanghai.myqcloud.com/index_home_activity_manage.png',
      identify: 5
    }, {
      title: '人才市场',
      image: 'https://lg-0nsng10k-1256175049.cos.ap-shanghai.myqcloud.com/index_home_recurit_manage.png',
      identify: 6
    }, {
      title: '计算工具',
      image: 'https://lg-0nsng10k-1256175049.cos.ap-shanghai.myqcloud.com/index_home_calculate_tool.png',
      identify: 7
    }],
  },

  // 接入微信小程序JavaScript SDK，定位当前城市
  getlocaltion() {
    var this_ = this;
    demo.reverseGeocoder({
      success: function(res) {
        if (res.status == 0) {
          var city = res.result.ad_info.city;
          app.data.globalCity = {
            'val': res.result.ad_info.adcode,
            'name': city
          };
          this_.setData({
            city: city,
            code: res.result.ad_info.adcode
          });
          this_.save_city(res.result.ad_info.adcode, city);
        }
      },
      fail: function(res) {
        console.log(res)
      }
    });
  },

  save_city: function(code, name) {
    wx.showLoading({
      title: '加载中',
    })
    var this_ = this;
    var params = {
      'user_id': app.data.userinfo.id,
      'city_code': code,
      'city_name': name
    }
    app.util.api('index/save_city_code', 'POST', params, function(data) {
      this_.hot_pro();
    });
  },

  /**
   * 权限检测
   */
  localtion: function(res) {
    var that = this;
    wx.getSetting({
      complete: function(res) {
        if (res.authSetting['scope.userLocation'] == undefined || res.authSetting['scope.userLocation']) {
          that.getlocaltion();
          that.setData({
            authStatus: true
          })
        } else {
          that.setData({
            authStatus: false
          })
        }
      }
    })
  },

  /**
   * 绑定微信
   */
  bindGetUserInfo: function() {
    var that = this;
    wx.getUserInfo({
      success: function(info) {
        var rawData = info['rawData'];
        var signature = info['signature'];
        var encryptedData = info['encryptedData'];
        var iv = info['iv'];
        var params = {
          "rawData": rawData,
          "signature": signature,
          'iv': iv,
          'encryptedData': encryptedData,
        };
        app.util.api('login/bind_wx', 'POST', params, function(data) {
          console.log(data)
          if (data.success == 1) {
            wx.showToast({
              title: data.msg,
            })
            that.setData({
              wxBind: true
            })
            that.loading();
          } else {
            wx.showToast({
              title: data.msg,
              icon: 'none'
            })
          }
        })
      }
    })
  },

  /**
   * 获取用户信息
   */
  loading: function(e) {
    var that = this;
    var params = {
      'type': 'userinfo'
    };
    app.util.api('userinfo/center', 'POST', params, function(data) {
      if (data.success == 1) {
        app.data.userinfo = data.data;
        that.setData({
          userinfo: data.data,
        })
        //若无公司信息则获取
        if (app.data.userinfo.company_info == undefined) {
          app.util.set_company_info();
        }
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none'
        })
      }
    })
  },

  //重新授权
  getAuth: function() {
    this.localtion();
  },

  // 选择城市
  choose_city: function() {
    wx.navigateTo({
      url: '/pages/index/location/city',
    })
  },

  // 发布
  pub: function() {
    wx.showActionSheet({
      itemList: ['自定义发布', '使用模板发布'],
      success: function(res) {

        if (res.tapIndex == 0) {
          wx.navigateTo({
            url: '/pages/product/publish',
          })
        } else {
          wx.navigateTo({
            url: '/pages/product/template',
          })
        }
      }
    })
  },

  // 我要录单
  orderShare: function() {
    wx.navigateTo({
      url: '/pages/client/release/index',
    })
  },

  //幻灯片点击
  slideClick: function(e) {
    if(this.data.show !== 1){
      var url = e.currentTarget.dataset.url;
      if (url !== '') {
        if (url.indexOf('com') !== -1) {
          wx.navigateTo({
            url: '/pages/webview/index?url=' + url,
          })
        } else {
          wx.navigateTo({
            url: url,
          })
        }
      }
    }
  },

  /**
   * 获取首页幻灯片
   */
  adv_img: function() {
    var that = this;
    var params = {
      'type': 'adv_img'
    }
    app.util.api('index/adv_img', 'GET', params, function(data) {
      if (data.success == 1) {
        that.setData({
          ImageList: data.data
        })
      }
    });
  },

  // 滚动通知
  rollNotice: function() {
    var that = this;
    var params = {
      'type': 'roll'
    }
    app.util.api('index/roll_notice', 'GET', params, function(data) {
      if (data.success == 1) {
        that.setData({
          msgList: data.data
        })
      }
    });
  },

  // 方块点击
  itemTap: function(e) {
    // 审核版本及手机号检测
    if (this.data.show !== 1) {
      if (!app.util.checkauth(app)) {
        return;
      }
    }
    var identify = e.currentTarget.dataset.identify
    if (identify == 0) { // 搜产品
      // var url = '/pages/pay/index'
      var url = '/pages/index/search/lists'
    } else if (identify == 1) { // 搜公司
      var url = '/pages/product/company/company_search'
    } else if (identify == 2) { // 找精英
      var url = '/pages/product/cream/cream_search'
    } else if (identify == 3) { // 抢客户
      var url = '/pages/client/list/index?des=抢客户'
    } else if (identify == 4) { // 展业地图
      var url = '/pages/customer/map/detail/map_detail'
    } else if (identify == 5) { // 活动管理
      var url = '/pages/index/activity/list/activity_list'
    } else if (identify == 6) { // 招聘管理
      var url = '/pages/index/recruit/recruit/list/recruit_list'
    } else if (identify == 7) { // 计算工具
      var url = '/pages/customer/tools/manth/repay_calculate'
    }
    wx.navigateTo({
      url: url,
    })
  },
  /**
   * 热门详情
   */
  noticeTap: function(e) {
    var item = e.currentTarget.dataset.item
    if (undefined == item) {
      wx.navigateTo({
        url: 'notice/list/index',
      })
    } else {
      wx.navigateTo({
        url: '/pages/webview/index?url=' + item.url,
      })
    }
  },


  /**
   * 产品点击
   */
  productTap: function(e) {
    var id = parseInt(e.currentTarget.dataset.id);
    //用户权限检测
    if (!app.util.checkauth(app)) {
      return;
    }
    wx.navigateTo({
      url: 'detail?id=' + id,
    })
  },

  /**
   * 首页热门产品
   */
  hot_pro: function() {
    var that = this;
    var params = {
      "type": "hot_pro"
    }
    params.city_code = app.data.globalCity.val;
    app.util.api('product/hot_pro', 'GET', params, function(data) {
      if (data.success == 1) {
        for (var k = 0, length = data.data.length; k < length; k++) {
          if (data.data[k].limit_months < 12) {
            data.data[k].limit_months = data.data[k].limit_months + '月';
          } else {
            data.data[k].limit_months = data.data[k].limit_months / 12 + '年';
          }
          if (data.data[k].open_days == 1) {
            data.data[k].open_days = '当日';
          } else if (data.data[k].open_days == 2) {
            data.data[k].open_days = '次日';
          } else if (data.data[k].open_days == 3) {
            data.data[k].open_days = '3天';
          } else if (data.data[k].open_days == 7) {
            data.data[k].open_days = '1周';
          } else if (data.data[k].open_days == 14) {
            data.data[k].open_days = '2周';
          } else if (data.data[k].open_days == 21) {
            data.data[k].open_days = '3周';
          } else if (data.data[k].open_days == 30) {
            data.data[k].open_days = '1月';
          } else {
            data.data[k].open_days = data.data[k].open_days + '日';
          }
        }
        that.setData({
          hot_pro: data.data
        })
      } else {
        that.setData({
          hot_pro: ''
        })
      }
      wx.hideLoading();
    })
  },

  /**
   * 红包信息
   */
  redbag: function() {
    var this_ = this;
    var params = {
      'type': 'red_bag'
    }
    app.util.api('redbag/bag', 'POST', params, function(data) {
      if (data.status == 200) {
        this_.setData({
          bagStatus: false,
          bag: data.data
        })
      } else {
        this_.setData({
          bagStatus: true
        })
      }
    })
  },

  // 领取红包
  receive_bag: function(e) {
    var this_ = this;
    var bag_id = e.currentTarget.dataset.id;
    var params = {
      'bag_id': bag_id
    }
    app.util.api('redbag/receive_bag', 'POST', params, function(data) {
      if (data.success) {
        wx.navigateTo({
          url: 'redbag/detail?id=' + bag_id,
        })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none'
        })
        this_.setData({
          bagStatus: true
        })
      }
    })
  },

  // 放弃红包
  give_up: function(e) {
    var this_ = this;
    var bag_id = e.currentTarget.dataset.id;
    var params = {
      'bag_id': bag_id
    }
    app.util.api('redbag/give_up', 'POST', params, function(data) {
      this_.setData({
        bagStatus: true
      });
      this_.check_bag();
    })
  },

  // 登录
  we_login: function() {
    var that = this;
    var token = wx.getStorageSync('token')
    // 若无token则登录请求token
    if (!token) {
      app.util.login(function(data) {
        if (data.success == 1) {
          //验证是否为游客
          if (data.data.user_nickname == '游客' && data.data.avatar == '') {
            that.setData({
              wxBind: false
            })
          } else {
            that.setData({
              wxBind: true
            })
          }
          app.data.userinfo = data.data;
          that.localtion();
          // 储存信息到本地
          wx.setStorageSync('token', data.other)

          //若无公司信息则获取
          if (app.data.userinfo.company_info == undefined) {
            app.util.set_company_info();
          }
        }
      })
    } else {
      var params = {
        'type': 'userinfo'
      };
      app.util.api('userinfo/center', 'POST', params, function(data) {
        if (data.success == 1) {
          //验证是否为游客
          if (data.data.user_nickname == '游客' && data.data.avatar == '') {
            that.setData({
              wxBind: false
            })
          } else {
            that.setData({
              wxBind: true
            })
          }
          app.data.userinfo = data.data;
          that.localtion();
          //设置用户信息
          that.setData({
            userinfo: data.data,
          })
          //若无公司信息则获取
          if (app.data.userinfo.company_info == undefined && app.data.userinfo.company_id !== null) {
            app.util.set_company_info();
          }

          // token失效，去获取新的token
        } else {
          app.util.login(function(data) {
            if (data.success == 1) {
              //验证是否为游客
              if (data.data.user_nickname == '游客' && data.data.avatar == '') {
                that.setData({
                  wxBind: false
                })
              } else {
                that.setData({
                  wxBind: true
                })
              }
              app.data.userinfo = data.data;
              that.localtion();
              // 储存信息到本地
              wx.setStorageSync('token', data.other)

              //若无公司信息则获取
              if (app.data.userinfo.company_info == undefined && app.data.userinfo.company_id !== null) {
                app.util.set_company_info();
              }
            }
          })
        }
      })
    }
  },

  // 校检红包
  check_bag: function() {
    var that = this;
    if (app.data.userinfo !== undefined) {
      that.redbag();
    } else {
      setTimeout(function() {
        that.check_bag()
      }, 100);
    }
  },

  // 审核版本检测
  show: function() {
    var that = this;
    var params = {
      'version': app.data.version
    };
    app.util.api('index/sys', 'GET', params, function(data) {
      app.data.showStatus = parseInt(data.data);
      that.setData({
        show: parseInt(data.data)
      })
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.we_login();
    this.adv_img();
    this.rollNotice();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          height: res.screenWidth * 0.45 + 'px',
          bagHeight: res.windowHeight,
          navH: app.globalData.navHeight
        })
      },
    });
    that.show();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.check_bag();
    if (app.data.globalCity !== undefined && app.data.globalCity.name !== this.data.city) {
      console.log(app.data.globalCity)
      this.save_city(app.data.globalCity.val, app.data.globalCity.name);
      this.setData({
        city: app.data.globalCity.name
      });
    }
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    if (that.data.show == true) {
      that.show();
    }
    that.hot_pro();
    that.adv_img();
    that.rollNotice();
    that.check_bag();
    wx.stopPullDownRefresh();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    return {
      title: '云推客-让贷款更简单',
      path: '/pages/index/index?user_id=' + app.data.userinfo.id,
      success: function(res) {
        var params = {
          "type": "share"
        }
        app.util.api('userinfo/share_vip', 'POST', params, function(data) {

        })
      },
      fail: function(res) {
        // 转发失败
      }
    }
  }
})